<template>
  <div class="app-container">
    <!-- 1. 压力设备查询表单 -->
    <el-form
        :model="deviceQueryParams"
        ref="deviceQueryRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
    >
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
            v-model="deviceQueryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleDeviceQuery"
        />
      </el-form-item>
      <el-form-item label="是否告警" prop="isAlarms">
        <el-input
            v-model="deviceQueryParams.isAlarms"
            placeholder="请输入是否告警（0=否/1=是）"
            clearable
            @keyup.enter="handleDeviceQuery"
        />
      </el-form-item>
      <el-form-item label="是否在线" prop="isLine">
        <el-input
            v-model="deviceQueryParams.isLine"
            placeholder="请输入是否在线（0=否/1=是）"
            clearable
            @keyup.enter="handleDeviceQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleDeviceQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetDeviceQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 2. 压力设备操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleDeviceAdd"
            v-hasPermi="['water:pressuredevice:add']"
        >新增设备</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="deviceSingle"
            @click="handleDeviceUpdate"
            v-hasPermi="['water:pressuredevice:edit']"
        >修改设备</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="deviceMultiple"
            @click="handleDeviceDelete"
            v-hasPermi="['water:pressuredevice:remove']"
        >删除设备</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleDeviceExport"
            v-hasPermi="['water:pressuredevice:export']"
        >导出设备</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getDeviceList"></right-toolbar>
    </el-row>

    <!-- 3. 压力设备表格（带展开行） - 关键修改1：添加style="width: 100%"强制占满父宽 -->
    <el-table
        v-loading="deviceLoading"
        :data="pressuredeviceList"
        @selection-change="handleDeviceSelectionChange"
        @expand-change="handleDeviceExpand"
        style="width: 100%"
    >
    <!-- 展开列 - 增加宽度并居中对齐，提升点击体验 -->
    <el-table-column type="expand" width="50" align="center">
      <template #default="scope">
        <!-- 调试信息：显示当前设备ID -->
        <div class="mb2 text-gray-500 text-sm">设备ID: {{ scope.row.deviceId }}</div>

        <!-- 3.1 传感器操作按钮（关联当前设备） -->
        <el-row :gutter="10" class="mb4">
          <el-col :span="2">
            <el-button
                type="primary"
                plain
                size="small"
                icon="Plus"
                @click="handleSensorAdd(scope.row.deviceId)"
                v-hasPermi="['water:pressuresensor:add']"
            >新增传感器</el-button>
          </el-col>
        </el-row>

        <!-- 3.2 传感器表格 - 关键修改2：添加style="width: 100%"，并优化列宽（固定+自适应） -->
        <el-table
            v-loading="sensorLoadingMap[scope.row.deviceId]"
            :data="sensorMap[scope.row.deviceId] || []"
            border
            size="small"
            style="width: 100%"
        >
        <!-- 空状态提示 -->
        <template #empty>
          暂无传感器数据，点击"新增传感器"添加
        </template>

        <!-- 关键修改3：固定短内容列宽度，长内容列用min-width自适应 -->
        <el-table-column label="传感器ID" align="center" prop="sensorId" width="120" />
        <el-table-column label="所属设备ID" align="center" prop="deviceId" width="120" />
        <el-table-column label="传感器名称" align="center" prop="sensorName" min-width="150" />  <!-- 自适应列：最小150px，剩余空间自动填充 -->
        <el-table-column label="传感器数值" align="center" prop="value" width="120" />
        <el-table-column label="是否告警" align="center" prop="isAlarms" width="120">
          <template #default="sScope">{{ sScope.row.isAlarms === 1 ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column label="传感器类型ID" align="center" prop="sensorTypeId" width="150" />
        <el-table-column label="更新时间" align="center" prop="updateDate" min-width="180" />  <!-- 时间列自适应，避免内容截断 -->
        <el-table-column label="操作" align="center" width="160" />
        </el-table>

        <!-- 3.3 传感器分页 -->
        <el-pagination
            v-show="(sensorPageMap[scope.row.deviceId]?.total || 0) > 0"
            :total="sensorPageMap[scope.row.deviceId]?.total || 0"
            :page-size="sensorPageMap[scope.row.deviceId]?.pageSize || 10"
            :current-page="sensorPageMap[scope.row.deviceId]?.pageNum || 1"
            @current-change="(val) => handleSensorPageChange(val, 'pageNum', scope.row.deviceId)"
            @size-change="(val) => handleSensorPageChange(val, 'pageSize', scope.row.deviceId)"
            layout="total, sizes, prev, pager, next, jumper"
            size="small"
            class="mt4"
        />
      </template>
    </el-table-column>

    <!-- 设备表格列 - 关键修改4：优化列宽分配（固定+自适应） -->
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="设备ID" align="center" prop="deviceId" width="120" />
    <el-table-column label="设备名称" align="center" prop="deviceName" min-width="150" />  <!-- 自适应列：填充剩余空间 -->
    <el-table-column label="是否告警" align="center" prop="isAlarms" width="120">
      <template #default="scope">{{ scope.row.isAlarms === 1 ? '是' : '否' }}</template>
    </el-table-column>
    <el-table-column label="是否在线" align="center" prop="isLine" width="120">
      <template #default="scope">{{ scope.row.isLine === 1 ? '是' : '否' }}</template>
    </el-table-column>
    <!-- 关键修改5：操作列宽度适配按钮，避免换行 -->
    <el-table-column label="操作" align="center" width="160" />
    </el-table>

    <!-- 4. 设备分页 -->
    <el-pagination
        v-show="deviceTotal > 0"
        :total="deviceTotal"
        v-model:page="deviceQueryParams.pageNum"
        v-model:limit="deviceQueryParams.pageSize"
        @pagination="getDeviceList"
        layout="total, sizes, prev, pager, next, jumper"
        style="width: 100%; margin-top: 16px;"
    />

    <!-- 5. 设备新增/修改对话框 -->
    <el-dialog :title="deviceTitle" v-model="deviceOpen" width="500px" append-to-body>
      <el-form ref="deviceFormRef" :model="deviceForm" :rules="deviceRules" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="deviceForm.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="是否告警" prop="isAlarms">
          <el-select v-model="deviceForm.isAlarms" placeholder="请选择是否告警">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否在线" prop="isLine">
          <el-select v-model="deviceForm.isLine" placeholder="请选择是否在线">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDevice">取消</el-button>
          <el-button type="primary" @click="submitDeviceForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 6. 传感器新增/修改对话框 -->
    <el-dialog :title="sensorTitle" v-model="sensorOpen" width="500px" append-to-body>
      <el-form ref="sensorFormRef" :model="sensorForm" :rules="sensorRules" label-width="80px">
        <el-form-item label="所属设备ID" prop="deviceId" v-if="false">
          <el-input v-model="sensorForm.deviceId" placeholder="请输入所属设备ID" />
        </el-form-item>
        <el-form-item label="传感器名称" prop="sensorName">
          <el-input v-model="sensorForm.sensorName" placeholder="请输入传感器名称" />
        </el-form-item>
        <el-form-item label="传感器数值" prop="value">
          <el-input v-model="sensorForm.value" placeholder="请输入传感器数值（如压力值）" />
        </el-form-item>
        <el-form-item label="是否告警" prop="isAlarms">
          <el-select v-model="sensorForm.isAlarms" placeholder="请选择是否告警">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="传感器类型ID" prop="sensorTypeId">
          <el-input v-model="sensorForm.sensorTypeId" placeholder="请输入传感器类型ID" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateDate">
          <el-date-picker
              clearable
              v-model="sensorForm.updateDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择更新时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSensor">取消</el-button>
          <el-button type="primary" @click="submitSensorForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PressureDeviceSensor">
import {
  listPressuredevice,
  getPressuredevice,
  delPressuredevice,
  addPressuredevice,
  updatePressuredevice
} from "@/api/water/pressuredevice";
import {
  listPressuresensor,
  getPressuresensor,
  delPressuresensor,
  addPressuresensor,
  updatePressuresensor
} from "@/api/water/pressuresensor";
import { getCurrentInstance } from "vue";
import { ref, reactive, toRefs } from "vue";

// 获取 proxy（原代码风格）
const { proxy } = getCurrentInstance();

// ========================== 压力设备相关状态 ==========================
// 设备列表数据
const pressuredeviceList = ref([]);
// 设备加载状态
const deviceLoading = ref(true);
// 搜索栏显示状态
const showSearch = ref(true);
// 设备选中ID集合
const deviceIds = ref([]);
// 设备单选状态（是否仅选中一行）
const deviceSingle = ref(true);
// 设备多选状态（是否未选中任何行）
const deviceMultiple = ref(true);
// 设备总数（分页用）
const deviceTotal = ref(0);
// 设备对话框显示状态
const deviceOpen = ref(false);
// 设备对话框标题
const deviceTitle = ref("");

// 设备表单数据（查询+新增修改）
const deviceData = reactive({
  // 设备查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: null,
    isAlarms: null,
    isLine: null
  },
  // 设备表单数据
  form: {
    deviceId: null,
    deviceName: null,
    isAlarms: null,
    isLine: null
  },
  // 设备表单验证规则
  rules: {
    deviceName: [
      { required: true, message: "请输入设备名称", trigger: "blur" },
      { max: 50, message: "设备名称长度不能超过50个字符", trigger: "blur" }
    ],
    isAlarms: [
      { required: true, message: "请选择是否告警", trigger: "change" }
    ],
    isLine: [
      { required: true, message: "请选择是否在线", trigger: "change" }
    ]
  }
});
const { queryParams: deviceQueryParams, form: deviceForm, rules: deviceRules } = toRefs(deviceData);

// ========================== 压力传感器相关状态 ==========================
// 传感器列表映射（key：设备ID，value：该设备下的传感器列表）
const sensorMap = ref({});
// 传感器加载状态映射（key：设备ID，value：加载状态）
const sensorLoadingMap = ref({});
// 传感器分页参数映射（key：设备ID，value：{pageNum, pageSize, total}）
const sensorPageMap = ref({});
// 传感器对话框显示状态
const sensorOpen = ref(false);
// 传感器对话框标题
const sensorTitle = ref("");
// 当前操作的设备ID（新增传感器时关联）
const currentDeviceId = ref("");

// 传感器表单数据
const sensorData = reactive({
  // 传感器表单数据
  form: {
    sensorId: null,
    deviceId: null,
    sensorName: null,
    value: null,
    isAlarms: null,
    sensorTypeId: null,
    updateDate: null
  },
  // 传感器表单验证规则
  rules: {
    sensorName: [
      { required: true, message: "请输入传感器名称", trigger: "blur" },
      { max: 50, message: "传感器名称长度不能超过50个字符", trigger: "blur" }
    ],
    value: [
      { required: true, message: "请输入传感器数值", trigger: "blur" },
      { pattern: /^-?\d+(\.\d+)?$/, message: "请输入有效的数值（整数或小数）", trigger: "blur" }
    ],
    isAlarms: [
      { required: true, message: "请选择是否告警", trigger: "change" }
    ],
    sensorTypeId: [
      { required: true, message: "请输入传感器类型ID", trigger: "blur" }
    ],
    updateDate: [
      { required: true, message: "请选择更新时间", trigger: "change" }
    ]
  }
});
const { form: sensorForm, rules: sensorRules } = toRefs(sensorData);

// ========================== 压力设备相关方法 ==========================
/**
 * 获取压力设备列表
 */
function getDeviceList() {
  deviceLoading.value = true;
  listPressuredevice(deviceQueryParams.value).then(response => {
    console.log("设备列表数据:", response); // 调试日志
    pressuredeviceList.value = response.rows || [];
    deviceTotal.value = response.total || 0;
    deviceLoading.value = false;
  }).catch((err) => {
    console.error("设备列表加载失败:", err); // 错误日志
    proxy.$modal.msgError("设备列表加载失败，请重试");
    deviceLoading.value = false;
  });
}

/**
 * 设备搜索按钮操作
 */
function handleDeviceQuery() {
  deviceQueryParams.value.pageNum = 1;
  getDeviceList();
}

/**
 * 设备重置按钮操作
 */
function resetDeviceQuery() {
  proxy.resetForm("deviceQueryRef");
  handleDeviceQuery();
}

/**
 * 设备多选事件（更新选中状态）
 */
function handleDeviceSelectionChange(selection) {
  deviceIds.value = selection.map(item => item.deviceId);
  deviceSingle.value = selection.length !== 1;
  deviceMultiple.value = !selection.length;
}

/**
 * 新增设备
 */
function handleDeviceAdd() {
  resetDeviceForm();
  deviceOpen.value = true;
  deviceTitle.value = "添加压力设备";
}

/**
 * 修改设备
 */
function handleDeviceUpdate(row) {
  resetDeviceForm();
  const _deviceId = row?.deviceId || deviceIds.value[0];
  getPressuredevice(_deviceId).then(response => {
    deviceForm.value = response.data;
    deviceOpen.value = true;
    deviceTitle.value = "修改压力设备";
  }).catch((err) => {
    console.error("获取设备详情失败:", err);
    proxy.$modal.msgError("获取设备详情失败");
  });
}

/**
 * 删除设备（支持单删/批量删）
 */
function handleDeviceDelete(row) {
  const _deviceIds = row?.deviceId || deviceIds.value;
  proxy.$modal.confirm(`是否确认删除压力设备编号为"${_deviceIds}"的数据项？`).then(() => {
    return delPressuredevice(_deviceIds);
  }).then(() => {
    // 删除设备后，清空对应的传感器数据
    if (Array.isArray(_deviceIds)) {
      _deviceIds.forEach(id => {
        delete sensorMap.value[id];
        delete sensorLoadingMap.value[id];
        delete sensorPageMap.value[id];
      });
    } else {
      delete sensorMap.value[_deviceIds];
      delete sensorLoadingMap.value[_deviceIds];
      delete sensorPageMap.value[_deviceIds];
    }
    getDeviceList();
    proxy.$modal.msgSuccess("设备删除成功");
  }).catch(() => {});
}

/**
 * 导出设备数据
 */
function handleDeviceExport() {
  proxy.download('water/pressuredevice/export', {
    ...deviceQueryParams.value
  }, `pressuredevice_${new Date().getTime()}.xlsx`);
}

/**
 * 提交设备表单（新增/修改）
 */
function submitDeviceForm() {
  proxy.$refs["deviceFormRef"].validate(valid => {
    if (valid) {
      const promise = deviceForm.value.deviceId
          ? updatePressuredevice(deviceForm.value)
          : addPressuredevice(deviceForm.value);

      promise.then(() => {
        deviceOpen.value = false;
        getDeviceList();
        proxy.$modal.msgSuccess(deviceForm.value.deviceId ? "设备修改成功" : "设备新增成功");
      }).catch((err) => {
        console.error("设备保存失败:", err);
        proxy.$modal.msgError("设备保存失败，请重试");
      });
    }
  });
}

/**
 * 取消设备操作
 */
function cancelDevice() {
  deviceOpen.value = false;
  resetDeviceForm();
}

/**
 * 重置设备表单
 */
function resetDeviceForm() {
  deviceForm.value = {
    deviceId: null,
    deviceName: null,
    isAlarms: null,
    isLine: null
  };
  proxy.resetForm("deviceFormRef");
}

// ========================== 压力传感器相关方法 ==========================
/**
 * 设备展开/收起事件（加载对应传感器）
 * @param {Object} row - 当前展开的设备行数据
 * @param {Array} expandedRows - 所有展开的行数据
 */
function handleDeviceExpand(row, expandedRows) {
  const deviceId = row.deviceId;
  console.log("展开/收起事件 - 设备ID:", deviceId, "当前行数据:", row);

  // 初始化当前设备的分页参数和加载状态
  if (!sensorPageMap.value[deviceId]) {
    sensorPageMap.value[deviceId] = {
      pageNum: 1,
      pageSize: 10,
      total: 0
    };
  }
  if (sensorLoadingMap.value[deviceId] === undefined) {
    sensorLoadingMap.value[deviceId] = false;
  }

  // 判断是否为展开操作（expandedRows包含当前行）
  const isExpand = expandedRows.some(item => item.deviceId === deviceId);
  console.log("是否展开:", isExpand);

  if (isExpand) {
    getSensorList(deviceId); // 加载传感器数据
  }
}

/**
 * 获取指定设备下的压力传感器列表
 * @param {string/number} deviceId - 设备ID
 */
function getSensorList(deviceId) {
  const pageParams = sensorPageMap.value[deviceId];
  sensorLoadingMap.value[deviceId] = true;

  // 传感器查询参数：关联设备ID + 分页
  const queryParams = {
    deviceId,
    pageNum: pageParams.pageNum,
    pageSize: pageParams.pageSize
  };

  console.log("请求传感器列表 - 参数:", queryParams);

  listPressuresensor(queryParams).then(response => {
    console.log("传感器列表返回数据:", response);
    sensorMap.value[deviceId] = response.rows || [];
    sensorPageMap.value[deviceId].total = response.total || 0;
    sensorLoadingMap.value[deviceId] = false;

    // 无数据时显示提示
    if ((response.rows || []).length === 0) {
      console.log(`设备${deviceId}暂无传感器数据`);
    }
  }).catch((err) => {
    console.error(`设备${deviceId}传感器加载失败:`, err);
    proxy.$modal.msgError("传感器列表加载失败，请重试");
    sensorLoadingMap.value[deviceId] = false;
  });
}

/**
 * 传感器分页变更（页码/页大小）
 * @param {number} val - 变更后的值
 * @param {string} type - 变更类型（pageNum/pageSize）
 * @param {string/number} deviceId - 设备ID
 */
function handleSensorPageChange(val, type, deviceId) {
  console.log(`传感器分页变更 - 设备ID:${deviceId}, 类型:${type}, 值:${val}`);
  sensorPageMap.value[deviceId][type] = val;

  // 页号变更时重置到第一页
  if (type === "pageSize") {
    sensorPageMap.value[deviceId].pageNum = 1;
  }

  getSensorList(deviceId);
}

/**
 * 新增传感器（关联指定设备）
 * @param {string/number} deviceId - 所属设备ID
 */
function handleSensorAdd(deviceId) {
  resetSensorForm();
  currentDeviceId.value = deviceId;
  sensorForm.value.deviceId = deviceId; // 绑定设备ID，不可修改
  sensorOpen.value = true;
  sensorTitle.value = "添加压力传感器";
}

/**
 * 修改传感器
 * @param {Object} row - 传感器行数据
 */
function handleSensorUpdate(row) {
  resetSensorForm();
  getPressuresensor(row.sensorId).then(response => {
    sensorForm.value = response.data;
    currentDeviceId.value = response.data.deviceId; // 记录所属设备ID
    sensorOpen.value = true;
    sensorTitle.value = "修改压力传感器";
  }).catch((err) => {
    console.error("获取传感器详情失败:", err);
    proxy.$modal.msgError("获取传感器详情失败");
  });
}

/**
 * 删除传感器
 * @param {Object} row - 传感器行数据
 */
function handleSensorDelete(row) {
  const _sensorId = row.sensorId;
  const deviceId = row.deviceId;
  proxy.$modal.confirm(`是否确认删除传感器编号为"${_sensorId}"的数据项？`).then(() => {
    return delPressuresensor(_sensorId);
  }).then(() => {
    getSensorList(deviceId); // 重新加载当前设备的传感器
    proxy.$modal.msgSuccess("传感器删除成功");
  }).catch(() => {});
}

/**
 * 提交传感器表单（新增/修改）
 */
function submitSensorForm() {
  proxy.$refs["sensorFormRef"].validate(valid => {
    if (valid) {
      const promise = sensorForm.value.sensorId
          ? updatePressuresensor(sensorForm.value)
          : addPressuresensor(sensorForm.value);

      promise.then(() => {
        sensorOpen.value = false;
        getSensorList(currentDeviceId.value); // 重新加载当前设备的传感器
        proxy.$modal.msgSuccess(sensorForm.value.sensorId ? "传感器修改成功" : "传感器新增成功");
      }).catch((err) => {
        console.error("传感器保存失败:", err);
        proxy.$modal.msgError("传感器保存失败，请重试");
      });
    }
  });
}

/**
 * 取消传感器操作
 */
function cancelSensor() {
  sensorOpen.value = false;
  resetSensorForm();
}

/**
 * 重置传感器表单
 */
function resetSensorForm() {
  sensorForm.value = {
    sensorId: null,
    deviceId: null,
    sensorName: null,
    value: null,
    isAlarms: null,
    sensorTypeId: null,
    updateDate: null
  };
  proxy.resetForm("sensorFormRef");
}

// 页面初始化：加载设备列表
getDeviceList();
</script>

<style scoped>
/* 调整展开行内传感器表格的间距 */
.mb2 {
  margin-bottom: 2px;
}
.mb4 {
  margin-bottom: 4px;
}
.mt4 {
  margin-top: 4px;
}
.text-gray-500 {
  color: #6b7280;
}
.text-sm {
  font-size: 12px;
}

/* 补充：确保父容器无额外内边距影响表格宽度 */
.app-container {
  padding: 16px; /* 保留必要内边距，避免内容贴边 */
  box-sizing: border-box; /* 确保padding不影响宽度计算 */
}
</style>